// pages/home/prodetail/prodetail.js
const api = require('../../../api/api.js');
var WxParse = require('../../../lib/wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    product: [],
    attrs: [],
    productId: "",
    attachments: [],
    cartAmount: 0,
    warn_number: 1,
    Domin: api.SCENE_HOST,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.getProdetail(options);
    that.getCartAmount();
  },

  getProdetail: function (options) {
    let that = this;
    wx.request({
      url: api.ProdetailGet,
      data: {
        product: options.id
      },
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function (res) {
        if (res.data.error_code === 0) {
          that.setData({
            product: res.data.product,
            productId: res.data.product.id,
            attachments: res.data.product.attachments,
            warn_number: res.data.product.warn_number
          });
          let properties = res.data.product.properties;
          var warn_number = res.data.product.warn_number;
          var attrsNumber = {
            "amount": warn_number
          };
          for (var i = 0; i < properties.length; i++) {
            let id = properties[i].id;
            if (id == 17) {
              // let attrs = [];
              let attrs1 = properties[i].attrs;
              for (var j = 0; j < attrs1.length; j++) {
                attrs1[j]["amount"] = warn_number
              }
              that.setData({
                attrs: attrs1,
                attrsNumber: attrsNumber
              });
            }
          }
          res.data.product.goods_desc = res.data.product.goods_desc.replace(/src="\//g, "src=\"http://zs.bocang.cc/");
          WxParse.wxParse('goodsDetail', 'html', res.data.product.goods_desc, that);
        }
      }
    });
  },

  jianBtnTap: function (e) {
    let that = this;
    var index = e.currentTarget.dataset.index;
    var attrs = this.data.attrs;
    var warn_number = that.data.warn_number;
    if (index !== "" && index != null) {
      if (attrs[parseInt(index)].amount > warn_number) {
        var amount = attrs[parseInt(index)].amount - parseInt(warn_number);
        attrs[parseInt(index)]["amount"] = amount
      }
      that.setData({
        attrs: attrs
      })
    }
  },

  bindNumberTap: function (e) {
    let that = this;
    var index = e.currentTarget.dataset.index;
    var attrs = that.data.attrs;
    var warn_number = that.data.warn_number;
    var detailValue = e.detail.value;
    that.setData({
      detailValue: detailValue
    })
    var number = attrs[parseInt(index)].number;
    if (parseInt(detailValue) == 0) {
      detailValue = parseInt(warn_number)
    }
    if (parseInt(detailValue) > parseInt(number)) {
      wx.showToast({
        title: "库存不足",
        image: "/images/icon/error_icon.png"
      });
      detailValue = parseInt(number);
      attrs[parseInt(index)].amount = parseInt(detailValue);
    } else {
      if (detailValue % warn_number != 0) {
        wx.showToast({
          title: "应为" + warn_number + "的倍数",
          image: "/images/icon/error_icon.png"
        });
      } else {
        attrs[parseInt(index)].amount = parseInt(detailValue);
      }
    }
    that.setData({
      attrs: attrs
    });
  },

  jiaBtnTap: function (e) {
    let that = this;
    var index = e.currentTarget.dataset.index;
    var attrs = that.data.attrs;
    var warn_number = that.data.warn_number;
    if (index !== "" && index != null) {
      var amount = attrs[parseInt(index)].amount + parseInt(warn_number);
      if (amount > attrs[parseInt(index)].number) {
        wx.showToast({
          title: "库存不足",
          image: "/images/icon/error_icon.png"
        });
      } else {
        attrs[parseInt(index)]["amount"] = amount
      }
    }
    that.setData({
      attrs: attrs
    })
  },

  CallPhoneTap: function () {
    wx.makePhoneCall({
      phoneNumber: api.PhoneCall //仅为示例，并非真实的电话号码
    })
  },

  addCartTap: function (event) {
    let that = this;
    var index = event.currentTarget.dataset.index;
    var attrs = that.data.attrs;
    var amount = attrs[parseInt(index)].amount
    var productId = that.data.productId + "";
    var attrsId = '{\"id\":' + "\"" + event.currentTarget.dataset.attrsId + "\"" + '}';
    wx.request({
      url: api.AddCart,
      data: {
        product: productId,
        property: attrsId,
        amount: amount
      },
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function(res) {
        if (res.data.error_code == 0) {
          wx.showToast({
            title: '已加入购物车',
            icon: "success",
            image: "/images/success.png"
          });
          that.getCartAmount();
        }
        if (res.data.error_code == 10001) {
          wx.showModal({
            title: '',
            content: '是否登录？',
            success: function (res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '../../login/login/login',
                });
              }
            }
          });
        }
        if (res.data.error_code == 400) {
          var error_desc = res.data.error_desc
          wx.showToast({
            title: error_desc,
            image: "/images/icon/error_icon.png"
          });
        }
        if (res.data.error_code == 403) {
          var error_desc = res.data.error_desc
          wx.showToast({
            title: "最少" + that.data.warn_number + "个起订",
            image: "/images/icon/error_icon.png"
          });
        }
      }
    })
  },

  getCartAmount: function () {
    let that = this;
    wx.request({
      url: api.CartGet,
      data: {

      },
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log("success");
        if (res.data.error_code === 0) {
          if (res.data.goods_groups.length > 0 && res.data.goods_groups[0].goods) {
            that.setData({
              cartAmount: res.data.goods_groups[0].goods.length,
            });
          }
        }
      },
    })
  },

  toCartTap: function () {
    wx.switchTab({
      url: '../../cart/index/index',
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})